package createModel.prototypeModel;

import java.io.*;
import java.util.Date;

/**
 * 2024/01/11
 * <p>
 * ZhangYi
 * Description 用户
 */
public class User implements Cloneable,Serializable{

    private static final long serialVersionUID = -1816190251661458590L;
    private String userName;
    private String password;
    private Date birthday;

    public User() {
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", birthday=" + birthday +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        // 原型模式的精髓: 重写clone方法, 使得对象可以被复制
        User obj = (User) super.clone();
        obj.birthday = (Date) this.birthday.clone();
        return obj;
    }


    public User deepCopy(){
        ByteArrayOutputStream bos  = null;
        ObjectOutputStream oos = null;

        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            // 写出到流中
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            User user = (User) ois.readObject();
            return user;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (oos != null) {
                    oos.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
